package com.example.experiment4;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SMSActivity extends AppCompatActivity {
    private static final String TAG = "SMSActivity";
    private static final int SEND_SMS_PERMISSION = 100;

    private TextView textViewSender;
    private TextView textViewContent;
    private IntentFilter receiveFilter;
    private IntentFilter sendFilter;
    private MessageReceiver    messageReceiver;
    private EditText editTextTo;
    private EditText editTestMsg;

    private SendStatusReceiver sendStatusReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);

        textViewSender = findViewById(R.id.sender);
        textViewContent = findViewById(R.id.content);

        receiveFilter = new IntentFilter();
        receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        messageReceiver = new MessageReceiver();
        registerReceiver(messageReceiver, receiveFilter);

        sendFilter = new IntentFilter();
        sendFilter.addAction("SENT_SMS_ACTION");
        sendStatusReceiver = new SendStatusReceiver();
        registerReceiver(sendStatusReceiver, sendFilter);
    }

    // 在AndroidManifest中也要设置接收和发送短信权限
//    <uses-permission android:name="android.permission.SEND_SMS" />
//    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    private void requestPermission() {
        //判断Android版本是否大于23
        // TODO:需要修改CALL_PHONE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(
                    this, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.SEND_SMS,
                                Manifest.permission.RECEIVE_SMS}, SEND_SMS_PERMISSION);
                return;
            } else {
                //已有权限
                sendSMS();
            }
        } else {
            //API 版本在23以下
        }
    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case SEND_SMS_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    sendSMS();
                } else {
                    // 拒绝授权
                    Toast.makeText(SMSActivity.this,
                            "CALL_PHONE Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void onClick(View source) {
        requestPermission();
    }

    private void sendSMS() {
        editTextTo = findViewById(R.id.to);
        editTestMsg = findViewById(R.id.msg_input);

        String content = editTestMsg.getText().toString().trim();
        // 模拟器号码：+1-555-521-5554
        String phone = editTextTo.getText().toString().trim();

        if (!TextUtils.isEmpty(content) && !TextUtils.isEmpty(phone)) {
            Intent sentIntent = new Intent("SENT_SMS_ACTION");
            PendingIntent pi = PendingIntent.getBroadcast(
                    SMSActivity.this, 0, sentIntent, 0);

            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phone, null, content, pi,
                    null);
        } else {
            Toast.makeText(this, "手机号或内容不能为空",
                    Toast.LENGTH_SHORT).show();
        }
    }

    class SendStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode() == RESULT_OK) {
                Toast.makeText(context, "发送成功",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "发送失败",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    // 运行Andriod Device Monitor，用Emulator Control给模拟器发送短信
    // Andriod Device Monitor的路径为：
    // C:\Users\Administrator\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
    class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[])bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }

            String address = messages[0].getOriginatingAddress();
            String fullMessage = "";
            for (SmsMessage message : messages) {
                fullMessage += message.getMessageBody();
            }

            textViewSender.setText(textViewSender.getText() + "  " +  address);
            textViewContent.setText(textViewContent.getText() + "  "  + fullMessage);
        }
    }
}
